from collections import OrderedDict

from django.shortcuts import render

from goods.models import GoodsPindao, SKU


def get_categories():
    categories = OrderedDict()

    pindao_all = GoodsPindao.objects.order_by('group_id', 'sequence')

    for pindao in pindao_all:
        group_id = pindao.group_id

        if group_id not in categories:
            categories[group_id] = {'channels': [],
                                    'sub_cats': []}

        cat1 = pindao.category

        categories[group_id]['channels'].append({'id': cat1.id,
                                                 'name': cat1.name,
                                                 'url': pindao.url})

        for cat2 in cat1.goodsleibie_set.all():
            cat2.sub_cats = []
            for cat3 in cat2.goodsleibie_set.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    return categories


def get_breadcrumb(category):
    breadcrumb = dict(
        cat1='',
        cat2='',
        cat3=''
    )
    if category.parent is None:
        breadcrumb['cat1'] = category

    elif category.goodsleibie_set.count() == 0:
        breadcrumb['cat3'] = category
        cat2 = category.parent
        breadcrumb['cat2'] = cat2
        breadcrumb['cat1'] = cat2.parent

    else:
        breadcrumb['cat2'] = category
        breadcrumb['cat1'] = category.parent

    return breadcrumb


def get_goods_and_spec(sku_id, request):
    try:
        sku = SKU.objects.get(id=sku_id)
        sku.images = sku.skuimage_set.all()
    except Exception as e:
        return render(request, '404.html')

    goods = sku.goods

    sku_specs = sku.skuguige_set.order_by('spec_id')
    sku_key = []
    for spec in sku_specs:
        sku_key.append(spec.option.id)

    skus = goods.sku_set.all()
    spec_sku_map = {}
    for s in skus:
        s_specs = s.skuguige_set.order_by('spec_id')
        key = []
        for spec in s_specs:
            key.append(spec.option.id)
        spec_sku_map[tuple(key)] = s.id

    goods_specs = goods.goodsguige_set.order_by('id')
    if len(sku_key) < len(goods_specs):
        return

    for index, spec in enumerate(goods_specs):
        key = sku_key[:]
        spec_options = spec.guigexuanxiang_set.all()
        for option in spec_options:
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))
        spec.spec_options = spec_options

    data = {
        'goods': goods,
        'goods_specs': goods_specs,
        'sku': sku
    }
    return data